<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">
          {{getTitleByName(nameOfPermission)}}列表查询
          <el-button link @click="delFav()" style="margin-bottom: 5px;" v-if="userFavorites?.length > 0">
            <svg-icon icon-class="stars" color="#E6A23C" />
          </el-button>
          <el-button link @click="addFav()" style="margin-bottom: 5px;" v-else>
            <svg-icon icon-class="star" />
          </el-button>
        </div>
        <div>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
        </div>
      </el-col>
    </el-row>
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <el-form-item label="明细项目类别编码" prop="itemTypeCode">
          <InputTagDialog v-model="listQuery.itemTypeCode" placeholder="明细项目类别编码" title="填写明细项目类别编码" />
        </el-form-item>
        <el-form-item label="明细项目类别名称" prop="itemTypeName">
          <el-input v-model="listQuery.itemTypeName" placeholder="明细项目类别名称" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="listQuery.state">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="item in getEnumList('CommonEnableDisable')" :label="item.key" :key="item.key">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">列表详情</div>
        <div>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
          -->
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Edit" @click="handleAdd">
            新增一级项目类别
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="arrChangeTreeFn(list)"
              row-key="id"
              fit
              highlight-current-row
              tooltip-effect="dark">
      <el-table-column align="center" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="明细项目类别编码" prop="itemTypeCode"  width="200px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><CodeTag :code="row.itemTypeCode" /></template>
      </el-table-column>
      <el-table-column align="center" label="明细项目类别名称" prop="itemTypeName" min-width="205px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.itemTypeName }}</template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="state" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('CommonEnableDisable')" :enum-key="row.state" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="上级明细项目类别" prop="parentId" min-width="255px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="list" :foreignIds="row.parentId" :foreignLabel="['itemTypeCode', 'itemTypeName']" /></template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <el-button type="primary" link @click="handleAdd1(row)" v-if="row.level === 1">新增二级项目类别</el-button>
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('')">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="selectRange(row)" v-if="row.level === 2">选择开支范围</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="明细项目类别编码" prop="itemTypeCode">
          <el-input v-model="obj.itemTypeCode" placeholder="请输入明细项目类别编码，最多输入50个字符" />
        </el-form-item>
        <el-form-item label="明细项目类别名称" prop="itemTypeName">
          <el-input v-model="obj.itemTypeName" placeholder="请输入明细项目类别名称，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="obj.state">
            <el-radio-button v-for="(item,index) in getEnumList('CommonEnableDisable')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级明细项目类别ID" prop="parentId" v-if="type === 2 && dialogType !== 'view'">
          <el-input v-model="itemTypeParentName" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime ? obj.createTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime ? obj.updateTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="dialogVisible1" :title="dialogTypeTitle1" width="70%" top="2vh">
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list1"
        border
        fit
        ref="rangeTabel"
        height="500"
        highlight-current-row
        tooltip-effect="dark"
        style="width: 100%;margin-bottom:20px"
        @selection-change="handleSelectionChange"
      >
      <!-- :reserve-selection="true"-->
        <el-table-column type="selection" width="39px" />
        <el-table-column align="center" type="index" label="序号" width="60px" />
        <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
        <el-table-column align="center" label="明细开支范围编码" prop="itemRangeCode" min-width="205px" sortable show-overflow-tooltip>
          <template v-slot="{row}">{{ row.itemRangeCode }}</template>
        </el-table-column>
        <el-table-column align="center" label="明细开支范围名称" prop="itemRangeName" min-width="205px" sortable show-overflow-tooltip>
          <template v-slot="{row}">{{ row.itemRangeName }}</template>
        </el-table-column>
        <el-table-column align="center" label="状态" prop="state" min-width="80px" sortable show-overflow-tooltip>
          <template v-slot="{row}">
            <EnumTag :enum-list="getEnumList('CommonEnableDisable')" :enum-key="row.state" />
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible1=false">关闭</el-button>
        <el-button v-show="dialogType !== 'view'" type="primary" @click="doConfirm1()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost, doPut, doDelete, doGetDownload} from '@/config/http'
import {customValidator, arrChangeTreeFn, alertErrorMsg, notifySuccess, getListPageSize, initListUpdate} from '@/config/common'
import InputTagDialog from "@/components/InputTag/inputTagDialog.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  itemTypeCode: null, // 明细项目类别编码
  itemTypeName: null, // 明细项目类别名称
  state: null, // 状态
  parentId: null, // 上级明细项目类别ID
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

export default {
  name: 'budgetItemType_nocache',
  components: {SvgIcon, InputTagDialog},
  mixins: [baseConfig],
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      routes: [],
      dialogVisible: false,
      dialogVisible1: false,
      dialogType: 'add',
      dialogType1: 'add',
      dialogTypeTitle: '新增',
      dialogTypeTitle1: '选择开支范围',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      type: 1,
      tableKey: 0,
      list: null,
      // listType: null,
      total: 0,
      listLoading: false,
      itemTypeParentName: '',
      list1: [],
      listQuery: {
        pageNum: 1,
        pageSize: getListPageSize(),
        sortField: 'id',
        sortType: 'desc',
        itemTypeCode: null,
        itemTypeName: null,
        state: '',
        parentId: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        itemTypeCode: [{ required: false, validator: customValidator, min: 0, max: 50, label: '明细项目类别编码', trigger: ['blur', 'change'] }],
        itemTypeName: [{ required: true, validator: customValidator, min: 0, max: 200, label: '明细项目类别名称', trigger: ['blur', 'change'] }],
        state: [{ required: true, validator: customValidator, min: 0, max: 20, label: '状态', trigger: ['blur', 'change'] }],
        parentId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '上级明细项目类别ID', trigger: ['blur', 'change'] }],
      },
      itemTypeList: initListStore().itemTypeList,
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  created() {
    this.nameOfPermission = 'budgetItemType'
    this.getFavorite(this.nameOfPermission)?.then(res => this.userFavorites = res)
    this.getList()
    // this.initList()
    this.getRangeData()
  },
  methods: {
    getListPageSize,
    arrChangeTreeFn,
    // async initList() {
    //   let p1 = doGet(this.svc, '/budget-item-type/page', {pageSize: this.listQuery.pageSize}, false)
    //   let resArray = await Promise.all([p1])
    //   this.itemTypeList = resArray[0]['records']
    // },
    getList() {
      this.listLoading = true
      let param = {
        pageSize: this.listQuery.pageSize,
        itemTypeCode: this.listQuery.itemTypeCode,
        itemTypeName: this.listQuery.itemTypeName,
        state: this.listQuery.state
      }
      doGet(this.svc, '/budget-item-type/page', param).then(res => {
        this.listLoading = false
        // 一级项目类别列表
        // this.listType = res['records'].filter(item => !item.parentId).reverse()
        // 树结构项目类别列表
        this.list = res['records']
        console.debug('this.list',this.list)
        // this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    getRangeData() {
      // this.listLoading = true
      doGet(this.svc, '/budget-item-range/page', {pageSize: this.listQuery.pageSize}).then(res => {
        // this.listLoading = false
        this.list1 = res['records'].reverse()
      }).catch(e => {
        console.error(e)
        // this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.type = row.level === 1 ? 1 : 2
      this.dialogType = 'edit'
      this.dialogTypeTitle = '编辑'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, row)
    },
    handleView(row) {
      this.type = row.level === 1 ? 1 : 2
      this.dialogType = 'view'
      this.dialogTypeTitle = '详情'
      this.dialogVisible = true
      this.checkStrictly = false
      this.obj = Object.assign({}, row)
      // if (this.type === 2) {
      //   this.obj.parentId = row.id
      //   this.itemTypeParentName = row.itemTypeCode + '-' + row.itemTypeName
      // }
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
      this.type = 1
    },
    handleAdd1(row) {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      // this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
      this.obj.parentId = row.id
      this.itemTypeParentName = row.itemTypeCode + '-' + row.itemTypeName
      this.type = 2
    },
    handleExport() {
      doGetDownload(this.svc, '/budget-item-type/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(this.svc, '/budget-item-type/' + row.id, {}).then(() => {
        notifySuccess('操作成功')
        this.getList()
        initListUpdate('itemTypeList', '/budget-item-type/page')
      })
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      if (this.dialogType === 'edit') {
        doPut(this.svc, '/budget-item-type/modify', this.obj).then(() => {
          notifySuccess('操作成功')
          this.getList()
          this.dialogVisible = false
          initListUpdate('itemTypeList', '/budget-item-type/page')
        })
      } else if (this.dialogType === 'add') {
        doPost(this.svc, '/budget-item-type/add', this.obj).then(() => {
          notifySuccess('操作成功')
          this.getList()
          this.dialogVisible = false
          initListUpdate('itemTypeList', '/budget-item-type/page')
        })
      }
    },
    selectRange(row) {
      this.dialogVisible1 = true
      this.obj = Object.assign({}, row)
        doGet(this.svc, '/budget-item-type-range/listByField', {field: 'itemTypeId', values: row.id}, false).then(res => {
          if (res.length > 0) {
            let ids = []
            res.map(item => {
              ids.push(item.itemRangeId)
            })
            doGet(this.svc, '/budget-item-range/ids', {ids: ids.join(',')}, false).then(r => {
              // 选中回显
              console.debug('r=============',r)
              if (r.length > 0) {
                this.$refs.rangeTabel.clearSelection();
                this.list1.forEach(item => {
                  r.forEach(row => {
                    if (item.id === row.id)
                    this.$refs.rangeTabel.toggleRowSelection(item, true);
                  })
                })
              } else {
                this.$refs.rangeTabel.clearSelection();
              }
            })
          } else {
            this.$refs.rangeTabel.clearSelection();
          }
        })
    },
    doConfirm1() {
      if (this.selectionList.length <= 0) {
        alertErrorMsg("请选择开支范围")
        return
      }
      let o = {}
      o.itemTypeId = this.obj.id
      o.itemRanges = []
      this.selectionList.map(item => {
        let i = {
          itemTypeId: this.obj.id,
          itemRangeId: item.id,
        }
        o.itemRanges.push(i)
      })
      doPost(this.svc, '/customBudgetItemType/saveBudgetItemTypeRange', o).then(_ => {
        notifySuccess('操作成功')
        this.getList()
        initListUpdate('itemTypeList', '/budget-item-type/page')
        this.dialogVisible1 = false
      })
    }
  }
}
</script>
